import sys
sys.path.append('../')
from flask import (
    Blueprint, flash, g, redirect, render_template, request, session, url_for,jsonify
)
from core.pre_load import *

'''网站逻辑'''
bp = Blueprint('ques', __name__, url_prefix='/ques')
@bp.route('/answer', methods=('GET','POST'))
def answer():
    ques = request.args.get('q')
    conditions = {}
    ques_words = tf.sc.cut(ques)
    all_city = False
    all_veg = False
    print(ques_words)

    for w in ques_words:
        if 'city' not in conditions.keys() and w in ['全国','各地']:
            all_city = True
        if 'veg' not in conditions.keys() and w in ['蔬菜','菜','植物']:
            all_veg = True
        if not all_veg and 'veg' not in conditions.keys() and w in tf.veg_words:
            conditions['veg'] = w
        if not all_city and 'city' not in conditions.keys() and w in tf.city_words:
            conditions['city'] = w
        if 'ind' not in conditions.keys() and w in ind_words:
            conditions['ind'] = w
        
    datas = {}
    resCode = 404
    if ('veg' not in conditions.keys() and not all_veg) or ('city' not in conditions.keys() and not all_city):
        datas={
            'msg':'请保证输入蔬菜和地区'
        }
        resCode = 206
    else:
        cql = qa.matchArticle(conditions)
        df = dbc.neo4j.run(cql).to_data_frame()
        sql = qa.matchPrice(conditions)
        df2 = dbc.readFromSQL(sql)
        if df.empty:
            datas = {
                'msg':'没有找到相关的数据'
            }
            resCode = 206
        else:
            datas = qa.toDict(df)
            if not df2.empty:
                datas['price'] = {
                    'date':list(df2['Date']),
                    'price':list(df2['Price'])
                }
            resCode = 200

    return jsonify(datas),resCode
    # datas = {
    #     'nodes':[
    #         [{'id':1,'name':'湖北','label':'11'},{'id':2,'name':'武汉','label':'11'}],
    #         [{'id':3,'name':'蔬菜','label':'22'},{'id':4,'name':'洋葱','label':'2'}],
    #     ],
    #     'articles':[
    #         {
    #             'id':5,
    #             'title':'title1',
    #             'text':'text1'
    #         }
    #     ],
    #     'edges':[
    #         {
    #             'id':6,
    #             'fromNodeId':1,
    #             'toNodeId':5,
    #             'label':'label1',
    #         },
    #         {
    #             'id':7,
    #             'fromNodeId':2,
    #             'toNodeId':5,
    #             'label':'label2',
    #         }
    #     ]
    # }
    
    return jsonify(datas)